import sensor, image, time, pyb
def biankuang():
    enable_lens_corr = False  # turn on for straighter lines...打开以获得更直的线条…

    # 设置核函数滤波，核内每个数值值域为[-128,127],核需为列表或元组
    kernel_size = 1  # kernel width = (size*2)+1, kernel height = (size*2)+1
    kernel = [-1, -1, -1,
              -1, +8, -1,
              -1, -1, -1]
    # 这个一个高通滤波器。见这里有更多的kernel
    # http://www.fmwconcepts.com/imagemagick/digital_image_filtering.pdf
    thresholds = [(0, 100)]  # grayscale thresholds设置阈值

    sensor.reset()  # 初始化 sensor.
    # 初始化摄像头

    sensor.set_pixformat(sensor.GRAYSCALE)  # or sensor.RGB565
    # 设置图像色彩格式，有RGB565色彩图和GRAYSCALE灰度图两种

    sensor.set_framesize(sensor.SVGA)  # or sensor.QVGA (or others)
    sensor.set_windowing([200, 66, 450, 450])
    # 设置图像像素大小
    sensor.skip_frames(10)  # 让新的设置生效
    clock = time.clock()  # 跟踪FPS帧率

    # 在OV7725 sensor上, 边缘检测可以通过设置sharpness/edge寄存器来增强。
    # 注意:这将在以后作为一个函数实现
    if (sensor.get_id() == sensor.OV7725):
        sensor.__write_reg(0xAC, 0xDF)
        sensor.__write_reg(0x8F, 0xFF)
    while True:
        clock.tick()  # 追踪两个snapshots()之间经过的毫秒数.
        img = sensor.snapshot().lens_corr(1.05)  # 拍一张照片，返回图像

        # img.morph(kernel_size, kernel)
        img.median(3, threshold=True, invert=True, percentile=0.5, offset=3)
        img.binary(thresholds)
        img.erode(3)
        img.dilate(2)
        img.erode(3)

        rects = img.find_rects([0, 0, 450, 450], threshold=910000)
        if rects != []:
            img.draw_rectangle(rects[0].x(), rects[0].y(), rects[0].w(), rects[0].h(), color=[0, 255, 0])
        print(rects)


# 调用示例
if __name__ == "__main__":
    biankuang()
